package com.cheyun.netsalev3.view

import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.MyPagedListAdapter
import com.cheyun.netsalev3.bean.RowX
import com.cheyun.netsalev3.databinding.ActivityMessageListBinding
import com.cheyun.netsalev3.utils.BaseActivity
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.InjectorUtils
import com.cheyun.netsalev3.utils.api.NetworkState
import com.cheyun.netsalev3.viewmodel.MessageListActivityViewModel

class MessageListActivity : BaseActivity<ActivityMessageListBinding>() {
    lateinit var adpter: MyPagedListAdapter<RowX>
    override fun initContentView(): Int {
        return R.layout.activity_message_list
    }

    override fun initViewModel(): ViewModel? {
        var factory = InjectorUtils.getMessageListActivityViewModelFactory()
        return ViewModelProviders.of(this, factory).get(MessageListActivityViewModel::class.java)

    }

    override fun initView() {
        adpter = MyPagedListAdapter(R.layout.message_list_item, binding.viewModel)
        var recyclerView = binding.root.findViewById<RecyclerView>(R.id.swipe_target)
        recyclerView.adapter = adpter

        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.viewModel?.refresh()
        }

    }

    override fun initData() {
        binding.viewModel?.listData?.observe(this, Observer { list ->
//            list.forEach {
//                c-> c.dateline = FunctionUtils.getMessageTime(c.dateline)
//            }
            adpter.submitList(list)
//            binding.linearLayout.visibility = if (list.size == 0) GONE else VISIBLE
        })
        binding.viewModel?.networkState?.observe(this, Observer {
            binding.swipeRefreshLayout.isRefreshing = it == NetworkState.LOADING
            adpter.setNetworkState(it)
        })

        binding.viewModel?.total?.observe(this, Observer {
            binding.linearLayout.visibility = if (it == 0) GONE else VISIBLE
        })
    }

    override fun onRestart() {
        super.onRestart()
        binding.viewModel?.refresh()
    }


}
